<script setup lang="ts">
import { mobileLogin, accountLogin, mnpLogin } from '@/api/account'
import { smsSend, queryTenantList } from '@/api/app'
import { getUserCenter, userEdit } from '@/api/user'
import { useLockFn } from '@/hooks/useLockFn'
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'
import { TUILogin } from '@tencentcloud/tui-core'

import cache from '@/utils/cache'
import { isWeixinClient } from '@/utils/client'

import { useLogin } from '@/stores/login'
import FuiCheckboxGroup from '@/components/firstui/fui-checkbox-group/fui-checkbox-group.vue'
import { getImInfoAPI } from '@/api/my'
import { ref } from 'vue'

const loginStore = useLogin()
enum LoginTypeEnum {
    MOBILE = 'mobile',
    ACCOUNT = 'account'
}
const closePopup = () => {
    console.log('closePopup', showLoginPopup.value)
    if (showLoginPopup.value) {
        return
    }

    loginStore.showLogin = false
}

enum LoginWayEnum {
    ACCOUNT = 1,
    MOBILE = 2
}

const isWeixin = ref(true)
const showLoginPopup = ref(false)
// #ifdef H5
isWeixin.value = isWeixinClient()
// #endif

const userStore = useUserStore()
const appStore = useAppStore()

const websiteConfig = computed(() => appStore.getWebsiteConfig)
const uCodeRef = shallowRef()
const loginWay = ref<LoginWayEnum>(LoginWayEnum.ACCOUNT)
const codeTips = ref('')
const isCheckAgreement = ref(false)
const loginData = ref<any>({})
const showTenantList = ref(false)
const formData = reactive({
    scene: '',
    username: '',
    password: '',
    code: '',
    mobile: ''
})

const tenantList = ref([])

const getTenantList = async () => {
    const { data } = await queryTenantList()

    tenantList.value = data.map((item: any) => {
        console.log(cache.getTenant(), item.id)
        return {
            text: item.name,
            id: item.id,
            subText: cache.getTenant() === item.id ? '当前' : ''
        }
    })
}

// 修改/忘记密码
const handleClick = (index: number) => {
    const tenant = tenantList.value[index]
    cache.set('tenantId', tenant.id)
}

const codeChange = (text: string) => {
    codeTips.value = text
}

const sendSms = async () => {
    if (!formData.mobile || formData.mobile.length !== 11) {
        showToast('手机号不合法')
        return
    }
    if (uCodeRef.value?.canGetCode) {
        await smsSend(formData.mobile)
        showToast('发送成功')
        uCodeRef.value?.start()
    }
}

const changeLoginWay = (type: LoginTypeEnum, way: LoginWayEnum) => {
    formData.scene = type
    loginWay.value = way
}

const loginFun = async (scene: LoginTypeEnum) => {
    try {
        await checkAgreement()
        if (scene == LoginTypeEnum.ACCOUNT) {
            if (!formData.username) return showToast('请输入账号/手机号码')
            if (!formData.password) return showToast('请输入密码')
        }
        if (scene == LoginTypeEnum.MOBILE) {
            if (!formData.mobile) return showToast('请输入手机号码')
            if (!formData.code) return showToast('请输入验证码')
        }
        uni.showLoading({
            title: '请稍后...'
        })

        let data
        switch (scene) {
            case LoginTypeEnum.MOBILE:
                data = await mobileLogin(formData)
                break
            default:
                data = await accountLogin(formData)
                break
        }

        if (data) {
            loginHandle(data)
        }
    } catch (error: any) {
        uni.hideLoading()
        showToast(error as string)
    }
}

const showToast = (tips: string) => {
    uni.showToast({
        title: tips,
        icon: 'none'
    })
}

/**
 * 异步登录处理函数
 * 该函数用于处理登录逻辑，包括使用访问令牌登录、获取用户信息、隐藏登录界面和显示登录成功提示。
 * @param {any} data - 登录接口返回的数据，包含访问令牌。
 */
const loginHandle = async (data: any) => {
    // 从返回数据中提取访问令牌
    const { access_token } = data

    // im登录
    await userStore.getImInfo()

    console.log('登录im信息', userStore.imInfo)
    const imInfo = userStore.imInfo

    TUILogin.login({
        SDKAppID: imInfo.config.sdkAppId && Number(imInfo.config.sdkAppId),
        userID: imInfo.account.userId,
        userSig: imInfo.account.userSig,
        useUploadPlugin: true, // If you need to send rich media messages, please set to true.
        framework: `vue${3}` // framework used vue2 / vue3
    }).catch((err) => {
        console.log('im错误信息', err)
    })

    // 使用访问令牌进行登录
    userStore.login(access_token)
    // 异步获取用户信息
    await userStore.getUser()
    // 隐藏登录界面
    loginStore.showLogin = false
    // 显示登录成功提示
    showToast('登录成功')
    // 隐藏加载动画
    uni.hideLoading()
    // 注释掉的代码为登录成功后跳转到首页的逻辑
    // uni.reLaunch({
    //     url: '/views/home/index'
    // })
}

const { lockFn: handleLogin } = useLockFn(loginFun)

const checkAgreement = async () => {
    if (!isCheckAgreement.value)
        return Promise.reject('请勾选底部已阅读并同意《服务协议》和《隐私协议》')
}
const { lockFn: wxLogin } = useLockFn(async () => {
    console.log('wxLogin', isCheckAgreement.value)
    try {
        await checkAgreement()
        // #ifdef MP-WEIXIN
        uni.showLoading({
            title: '请稍后...'
        })
        const { code }: any = await uni.login({
            provider: 'weixin'
        })
        const data = await mnpLogin(code)
        loginData.value = data
        const { access_token } = data
        console.log('mnpLogin', data)
        // 临时用户没有昵称
        userStore.login(access_token)

        const res = await getUserCenter()

        // getImInfoAPI()
        console.log('getUserCenter', res)
        if (!res.data.appUser.nickname) {
            uni.hideLoading()
            userStore.temToken = access_token
            showLoginPopup.value = true
            return
        }

        loginHandle(data)
        // #endif
    } catch (error) {
        showToast(error as string)
    }
})

const handleUpdateUser = async (value: any) => {
    await userEdit(value)
    showLoginPopup.value = false
    loginHandle(loginData.value)
}

onShow(async () => {
    try {
        if (userStore.isLogin) {
            uni.showLoading({
                title: '请稍后...'
            })
            // await userStore.getUser()
            uni.hideLoading()
            // uni.navigateBack()
        }
    } catch (error: any) {
        uni.hideLoading()
    }
})

// onLoad(async () => {
//     // 清空用户信息
//     // userStore.logout()
//     // 获取租户列表
//     getTenantList()
//
//     if (userStore.isLogin) {
//         // 已经登录 => 首页
//         uni.reLaunch({
//             url: '/pages/index/index'
//         })
//         return
//     }
// })
</script>

<template>
    <fui-bottom-popup :show="loginStore.showLogin" @close="closePopup">
        <view class="login-box" v-if="!showLoginPopup">
            <view
                class="bg-white login min-h-full flex flex-col items-center px-[40rpx] pt-[80rpx] box-border"
            >
                <view class="fixed flex justify-end right-4 top-4">
                    <u-icon
                        name="setting"
                        color="#4D72F6"
                        :size="48"
                        @click="showTenantList = true"
                    ></u-icon>
                    <fui-actionsheet
                        :itemList="tenantList"
                        title="租户列表"
                        :show="showTenantList"
                        v-model="showTenantList"
                        :safe-area-inset-bottom="true"
                        @click="handleClick"
                    ></fui-actionsheet>
                </view>
                <view class="user-info flex justify-center items-center">
                    <image
                        style="width: 200rpx"
                        mode="widthFix"
                        :src="$getImg('/img/logo/logo.png')"
                    />
                </view>
                <view class="mt-4 text-xl font-medium">{{ appStore.config.website?.name }}</view>
                <view class="w-full pb-[60rpx]">
                    <!-- #ifndef MP-WEIXIN -->
                    <u-form borderBottom>
                        <template v-if="loginWay == LoginWayEnum.ACCOUNT">
                            <u-form-item borderBottom>
                                <u-icon
                                    class="mr-2"
                                    :size="36"
                                    :name="$getImg('/img/images/icon/icon_user.png')"
                                />
                                <u-input
                                    class="flex-1"
                                    v-model="formData.username"
                                    :border="false"
                                    placeholder="请输入手机号"
                                />
                            </u-form-item>
                            <u-form-item borderBottom>
                                <u-icon
                                    class="mr-2"
                                    :size="36"
                                    :name="$getImg('/img/images/icon/icon_password.png')"
                                />
                                <u-input
                                    class="flex-1"
                                    v-model="formData.password"
                                    type="password"
                                    placeholder="请输入密码"
                                    :border="false"
                                />
                            </u-form-item>
                        </template>
                        <template v-if="loginWay == LoginWayEnum.MOBILE">
                            <u-form-item borderBottom>
                                <u-icon
                                    class="mr-2"
                                    :size="36"
                                    :name="$getImg('/img/images/icon/icon_mobile.png')"
                                />
                                <u-input
                                    class="flex-1"
                                    v-model="formData.mobile"
                                    :border="false"
                                    placeholder="请输入手机号码"
                                />
                            </u-form-item>
                            <u-form-item borderBottom>
                                <u-icon
                                    class="mr-2"
                                    :size="36"
                                    :name="$getImg('/img/images/icon/icon_code.png')"
                                />
                                <u-input
                                    class="flex-1"
                                    v-model="formData.code"
                                    placeholder="请输入验证码"
                                    :border="false"
                                />
                                <view
                                    class="border-l border-solid border-0 border-light pl-3 leading-4 ml-3 w-[180rpx]"
                                    @click="sendSms"
                                >
                                    <u-verification-code
                                        ref="uCodeRef"
                                        :seconds="60"
                                        @change="codeChange"
                                        change-text="x秒"
                                    />
                                    <text :class="formData.mobile ? 'text-primary' : 'text-muted'">
                                        {{ codeTips }}
                                    </text>
                                </view>
                            </u-form-item>
                        </template>
                    </u-form>
                    <view class="mt-[60rpx]">
                        <u-button
                            type="primary"
                            shape="circle"
                            @click="handleLogin(formData.scene)"
                        >
                            登 录
                        </u-button>
                    </view>

                    <view class="text-content flex justify-between mt-[40rpx]">
                        <view class="flex-1">
                            <view
                                v-if="loginWay == LoginWayEnum.MOBILE"
                                @click="changeLoginWay(LoginTypeEnum.ACCOUNT, LoginWayEnum.ACCOUNT)"
                            >
                                账号密码登录
                            </view>
                            <view
                                v-if="loginWay == LoginWayEnum.ACCOUNT"
                                @click="changeLoginWay(LoginTypeEnum.MOBILE, LoginWayEnum.MOBILE)"
                            >
                                短信验证码登录
                            </view>
                        </view>

                        <navigator url="/pages/register/register" hover-class="none"
                            >注册账号</navigator
                        >
                    </view>
                    <!-- #endif -->

                    <!-- #ifdef MP-WEIXIN -->
                    <view class="mt-[80rpx]" v-if="isWeixin">
                        <fui-divider>一键登录</fui-divider>
                        <div class="flex justify-center mt-[40rpx]">
                            <div
                                v-if="isWeixin"
                                class="flex flex-col items-center"
                                @click="wxLogin"
                            >
                                <img
                                    :src="$getImg('/img/images/icon/icon_wx.png')"
                                    class="w-[80rpx] h-[80rpx]"
                                />
                            </div>
                        </div>
                    </view>
                    <!-- #endif -->
                </view>
                <view class="mt-[40rpx] flex-row gap-[20rpx]">
                    <fui-checkbox
                        @change="isCheckAgreement = !isCheckAgreement"
                        :checked="isCheckAgreement"
                        shape="circle"
                        scaleRatio="0.8"
                    >
                    </fui-checkbox>
                    <view class="flex text-xs">
                        已阅读并同意
                        <view @click.stop>
                            <navigator
                                class="text-primary"
                                hover-class="none"
                                url="/views/subViews/common/serviceProtocol?type=1"
                            >
                                《用户协议》
                            </navigator>
                        </view>

                        和
                        <view @click.stop>
                            <navigator
                                class="text-primary"
                                hover-class="none"
                                url="/views/subViews/common/serviceProtocol?type=2"
                            >
                                《隐私协议》
                            </navigator>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <mplogin-popup
            v-else
            v-model:show="showLoginPopup"
            :logo="websiteConfig.logo"
            :title="websiteConfig.name"
            @update="handleUpdateUser"
        />
    </fui-bottom-popup>
    <!--    <mplogin-popup-->
    <!--        v-model:show="showLoginPopup"-->
    <!--        :logo="websiteConfig.logo"-->
    <!--        :title="websiteConfig.name"-->
    <!--        @update="handleUpdateUser"-->
    <!--    />-->
</template>

<style scoped lang="scss">
.login-box {
    height: 60vh;
}
</style>
